package com.daqian.mall.config;

import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;


@Configuration
@EnableTransactionManagement
@Slf4j
public class MybatisConfig {

//    @Autowired
//    private DataSource dataSource;

    @Resource
    private MybatisProperties myBatisProperties;

    /**
     * @param dataSource 以参数传进的方式，springboot会根据引用自动地注入dataSource
     * @return
     * @throws Exception
     */
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) throws Exception {
        log.info("[ config SqlSessionFactoryBean ]");
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //添加模型
        bean.setTypeAliasesPackage(myBatisProperties.getTypeAliasesPackage());

        //分页插件
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("reasonable", "true");
        properties.setProperty("supportMethodsArguments", "true");
        properties.setProperty("returnPageInfo", "check");
        properties.setProperty("params", "count=countSql");
        pageHelper.setProperties(properties);

        //添加插件
        bean.setPlugins(new Interceptor[]{pageHelper});

        //添加XML目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            List<org.springframework.core.io.Resource> mapperLocations = new ArrayList<>();
            String[] locationArr = myBatisProperties.getMapperLocations();
            for (int i = 0; i < locationArr.length; i++) {
                mapperLocations.addAll(new ArrayList<>(Arrays.asList(resolver.getResources(locationArr[i]))));
            }
            bean.setMapperLocations(mapperLocations.toArray(new org.springframework.core.io.Resource[mapperLocations.size()]));
            return bean;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

}